package com.rednose.videoplayer.adapters;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.rednose.videoplayer.model.MediaFiles;
import com.rednose.videoplayer.R;
import com.rednose.videoplayer.utils.Utility;
import com.rednose.videoplayer.activities.VideoPlayerActivity;
import com.rednose.videoplayer.controller.LoginController;
import com.rednose.videoplayer.controller.PlayListController;
import com.rednose.videoplayer.model.ListVideo;
import com.rednose.videoplayer.model.User;

import java.io.File;
import java.util.ArrayList;

public class VideoFilesAdapter extends RecyclerView.Adapter<VideoFilesAdapter.ViewHolder> {

    private ArrayList<MediaFiles> videoList;
    private Context context;
    BottomSheetDialog bottomSheetDialog;
    private int viewType;

    public VideoFilesAdapter(ArrayList<MediaFiles> videoList, Context context, int viewType) {
        this.videoList = videoList;
        this.context = context;
        this.viewType = viewType;
    }

    @NonNull
    @Override
    public VideoFilesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.video_item, parent, false);
        return new ViewHolder(view);
    }

    //ViewHolder的数据绑定
    @Override
    public void onBindViewHolder(@NonNull VideoFilesAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {

        holder.videoName.setText(videoList.get(position).getDisplayName());//设置视频名称

        double milliSeconds = Double.parseDouble(videoList.get(position).getDuration());//获取视频时长
        holder.videoDuration.setText(Utility.timeConversion((long) (milliSeconds)));//转化格式，设置视频时长

        holder.videoSize.setText(android.text.format.Formatter.formatFileSize(
                context, Long.parseLong(videoList.get(position).getSize())));//设置视频大小

        //设置视频缩略图
        Glide.with(context)
                .load(videoList.get(position).getPath())
                .into(holder.thumbNail);

        //设置菜单的点击事件
        if (viewType == 0){
            holder.menu_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bottomSheetDialog = new BottomSheetDialog(context, R.style.BottomSheetTheme);       //创建底部弹窗
                    View bsView = LayoutInflater.from(context).inflate(R.layout.video_bs_layout,
                            v.findViewById(R.id.bottom_sheet));                                         //加载底部弹窗布局
                    bsView.findViewById(R.id.bs_play).setOnClickListener(new View.OnClickListener() {

                        public void onClick(View v) {
                            holder.itemView.performClick();                                 //模拟点击事件,跳转播放视频的活动
                            bottomSheetDialog.dismiss();                                    //关闭底部弹窗
                        }
                    });
                    bsView.findViewById(R.id.bs_add_to_list).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            PlayListController playListController = new PlayListController(context);  //创建播放列表控制器
                            LoginController loginController = new LoginController(context);          //创建登录控制器
                            User user = loginController.getUser(Utility.getCurrentUser(context));
                            int userID = user.getUserID();     //获取用户
                            String mediaID = videoList.get(position).getId();                        //获取视频ID
                            ListVideo listVideo = new ListVideo(mediaID,userID,-1);                                   //创建一个列表视频对象
                            playListController.addToPlayListTail(listVideo, user);               //添加到播放列表

                            Toast.makeText(context, "添加到列表末尾", Toast.LENGTH_SHORT).show();  //提示添加到列表
                            bottomSheetDialog.dismiss();                                      //关闭底部弹窗
                        }
                    });
                    bsView.findViewById(R.id.bs_rename).setOnClickListener(new View.OnClickListener(){


                        public void onClick(View view) {
                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);   //创建一个弹窗
                            alertDialog.setTitle("改名为");                                        //设置标题
                            EditText editText = new EditText(context);                            //创建一个编辑框
                            String path = videoList.get(position).getPath();                      //获取视频路径
                            final File file = new File(path);                                       //创建一个文件对象
                            String videoName = file.getName();                                      //获取视频名称
                            videoName = videoName.substring(0, videoName.lastIndexOf("."));     //去掉后缀名
                            editText.setText(videoName);                                            //设置编辑框的文本
                            alertDialog.setView(editText);                                          //设置弹窗的视图
                            editText.requestFocus();                                                //获取焦点

                            //设置弹窗的确定按钮,点击后改名,并刷新适配器
                            alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener(){

                                @Override
                                public void onClick(DialogInterface dialogInterface, int which) {
                                    if (TextUtils.isEmpty(editText.getText().toString())) {
                                        Toast.makeText(context, "无法重命名为空", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    String onlyPath = file.getParentFile().getAbsolutePath();   //获取视频的父路径
                                    String ext = file.getAbsolutePath();                        //获取视频的绝对路径
                                    ext = ext.substring(ext.lastIndexOf("."));              //获取视频的后缀名
                                    String newPath = onlyPath + "/" + editText.getText().toString() + ext;  //新的视频路径,改名后的路径
                                    File newFile = new File(newPath);                          //新的文件对象
                                    boolean rename = file.renameTo(newFile);                    //改名
                                    if(rename) {
                                        ContentResolver resolver = context.getApplicationContext().getContentResolver();  //获取内容解析器
                                        resolver.delete(MediaStore.Files.getContentUri("external"),           //删除媒体库中的视频
                                                MediaStore.MediaColumns.DATA + "=?", new String[]
                                                        {file.getAbsolutePath()});
                                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);              //通知媒体库更新
                                        intent.setData(Uri.fromFile(newFile));                                          //设置更新的路径
                                        context.getApplicationContext().sendBroadcast(intent);                          //发送广播

                                        notifyDataSetChanged();                                                         //刷新适配器
                                        Toast.makeText(context, "改名成功", Toast.LENGTH_SHORT).show();                 //提示改名成功

                                        SystemClock.sleep(200);                                                     //延时200毫秒
                                        ((Activity) context).recreate();                                                //重启活动
                                    }else {
                                        Toast.makeText(context, "改名失败", Toast.LENGTH_SHORT).show();                 //提示改名失败
                                    }
                                }
                            });
                            alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {         //设置弹窗的取消按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();                                                      //关闭弹窗
                                }
                            });
                            alertDialog.create().show();                                    //显示弹窗
                            bottomSheetDialog.dismiss();                                    //关闭底部弹窗
                        }
                    });
                    bsView.findViewById(R.id.bs_share).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Uri uri = Uri.parse(videoList.get(position).getPath());                 //获取视频路径
                            Intent shareIntent = new Intent(Intent.ACTION_SEND);                    //创建分享意图
                            shareIntent.setType("video/*");                                         //设置分享类型
                            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);                         //设置分享的视频路径
                            context.startActivity(Intent.createChooser(shareIntent, "分享到"));  //启动分享
                            bottomSheetDialog.dismiss();                                          //关闭底部弹窗
                        }
                    });
                    bsView.findViewById(R.id.bs_delete).setOnClickListener(new View.OnClickListener(){
                        public void onClick(View v) {
                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);   //创建一个弹窗
                            alertDialog.setTitle("删除视频");                                      //设置标题
                            alertDialog.setMessage("确定要删除吗?");                                //设置消息
                            alertDialog.setPositiveButton("删除", new DialogInterface.OnClickListener(){  //设置确定按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri contentUri = ContentUris                                        //获取视频的Uri
                                            .withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                                                    Long.parseLong(videoList.get(position).getId()));
                                    File file = new File(videoList.get(position).getPath());           //创建文件对象
                                    boolean delete = file.delete();                                    //删除文件
                                    if(delete) {
                                        context.getContentResolver().delete(contentUri, null, null);
                                        videoList.remove(position);                                             //移除视频
                                        notifyItemRemoved(position);                                            //通知移除视频
                                        notifyItemRangeChanged(position, videoList.size());                     //通知范围改变
                                        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();       //提示删除成功
                                    }else {
                                        Toast.makeText(context, "删除失败", Toast.LENGTH_SHORT).show();       //提示删除失败
                                    }
                                }
                            });
                            alertDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {         //设置取消按钮
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();                                                  //关闭弹窗
                                }
                            });
                            alertDialog.create().show();                                    //显示弹窗
                            bottomSheetDialog.dismiss();                                    //关闭底部弹窗
                        }

                    });

                    bsView.findViewById(R.id.bs_properties).setOnClickListener(new View.OnClickListener(){

                        @Override
                        public void onClick(View view) {
                            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);     //创建一个弹窗
                            alertDialog.setTitle("属性");                                     //设置标题

                            String one = "文件名: " + videoList.get(position).getDisplayName();           //设置属性，文件名

                            String path = videoList.get(position).getPath();                            //获取视频路径
                            int indexOfPath = path.lastIndexOf("/");
                            String two = "路径: " + path.substring(0, indexOfPath);                     //设置属性，路径
                            //设置属性，大小
                            String three = "大小: " + android.text.format.Formatter
                                    .formatFileSize(context, Long.parseLong(videoList.get(position).getSize()));

                            String four = "时长: " + Utility.timeConversion((long) milliSeconds);                 //设置属性，时长

                            String namewithFormat = videoList.get(position).getDisplayName();           //获取视频名称
                            int index = namewithFormat.lastIndexOf(".");
                            String format = namewithFormat.substring(index + 1);
                            String five = "格式: " + format;                                          //设置属性，格式

                            MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();    //创建一个媒体元数据检索器
                            metadataRetriever.setDataSource(videoList.get(position).getPath());         //设置数据源
                            String height = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);    //获取视频高度
                            String width = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);      //获取视频宽度
                            String six = "分辨率: " + width + "x" + height;                         //设置属性，分辨率

                            alertDialog.setMessage(one + "\n\n" + two + "\n\n" + three + "\n\n" + four +
                                    "\n\n" + five + "\n\n" + six);                                                  //设置消息
                            alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {     //设置确定按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {                        //点击确定按钮后
                                    dialog.dismiss();                                                           //关闭弹窗
                                }
                            });
                            alertDialog.show();                                                             //显示弹窗
                            bottomSheetDialog.dismiss();                                                    //关闭底部弹窗
                        }
                    });

                    bottomSheetDialog.setContentView(bsView);                               //设置底部弹窗的布局
                    bottomSheetDialog.show();                                               //显示底部弹窗
                }
            });
        }else {
            holder.menu_more.setVisibility(View.GONE);
            holder.videoName.setTextColor(Color.WHITE);
            holder.videoSize.setTextColor(Color.WHITE);
        }

        //设置整个控件item的点击事件，
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转播放视频的活动
                Intent intent = new Intent(context, VideoPlayerActivity.class);
                intent.putExtra("position",position);                                       //传递视频位置
                intent.putExtra("video_title", videoList.get(position).getDisplayName());   //传递视频名称
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("videoArrayList",videoList);                        //传递视频列表
                intent.putExtras(bundle);                                                         //传递bundle
                context.startActivity(intent);
                if (viewType == 1) {                                                            //如果是播放列表，结束当前活动
                    ((Activity) context).finish();
                }
            }
        });
    }
    @Override
    public int getItemCount() {
        return videoList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView thumbNail, menu_more;
        TextView videoName, videoDuration, videoSize;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            thumbNail = itemView.findViewById(R.id.thumbnail);
            menu_more = itemView.findViewById(R.id.video_menu_more);
            videoName = itemView.findViewById(R.id.video_name);
            videoDuration = itemView.findViewById(R.id.video_duration);
            videoSize = itemView.findViewById(R.id.video_size);
        }
    }


        //更新视频文件，传入视频文件列表
        public void  updateVideoFiles(ArrayList<MediaFiles> files) {
        videoList = new ArrayList<>();                                  //更新视频文件
        videoList.addAll(files);                                        //添加所有的视频文件
        notifyDataSetChanged();                                         //通知数据已经改变
    }

}
